#------------------------------------------------------------------------------------------------
# The documentation written by Voinage was used as a template for this addon
# http://wiki.xbmc.org/?title=HOW-TO_write_plugins_for_XBMC
#
# This addon is licensed with the GNU Public License, and can freely be modified
# http://www.gnu.org/licenses/gpl-2.0.html
#------------------------------------------------------------------------------------------------
import urllib,urllib2,re,os
import scrapers
try:
        import xbmcplugin,xbmcgui
except:
        pass
#------------------------------------------------------------------------------------------------
HttpHost = "http://tugatesting.googlecode.com/svn/trunk/channels/"
RootUrl = HttpHost+"categories.txt"
#------------------------------------------------------------------------------------------------
MODE_INDEX = 1
MODE_VIDEOLINKS = 3
MODE_AUDIOLINKS = 4
def UpdateScraperFile():
        url = HttpHost.replace('channels/','datadir/plugin.video.tugatv/scrapers.txt')
        scraper = None
        scraper = scrapers.urltools.LoadUrl(url)
        try:
                None#scraper = scrapers.urltools.LoadUrl(url)
        except:
                print 'Error updating scraper file: '+url
                return
        #print scraper

        filename = os.path.join( os.getcwd(), "scrapers.py" ) 
        f = open(filename,"w")
        #allLines = f.write(scraper)
        try:
                allLines = f.write(scraper)
        except:
                print 'Error saving scraper file: '
        f.close()

#------------------------------------------------------------------------------------------------
def INDEX(channel):
        params=scrapers.urltools.GetParams(channel)
        name = urllib.unquote_plus(params['name'])
        startndx = 0
        try:
            startndx = int(params['startndx'])
        except:
            pass

        pDialog = xbmcgui.DialogProgress()
        ret = pDialog.create(name, 'Opening Video Folder...')

        scraper = urllib.unquote_plus(params['scraper'])
        url = urllib.unquote_plus(params['url'])
        scraperobj = scrapers.GetScraperObj(scraper)

        print 'Scraping... '+url+' startndx: '+str(startndx)
        videolist = scraperobj.Scrape(url,startndx)

        #if url.endswith(".txt"):
        #    videolist.sort()

        for line in videolist:
            try:
                icon=line['icon']
            except:
                icon=''
            if line['type']=='dir':
                addDir(line['name'], line['url'], line['scraper'], MODE_INDEX, '', scrapers.urltools.DictToUrl(line))
            elif line['type']=='video':
                print 'CHANNEL: '+scrapers.urltools.DictToUrl(line)
                addDownLinkVideo(line['name'], line['url'], line['scraper'],MODE_VIDEOLINKS,icon,scrapers.urltools.DictToUrl(line))
            elif line['type']=='audio':
                print 'CHANNEL: '+scrapers.urltools.DictToUrl(line)
                addDownLinkAudio(line['name'], line['url'], line['scraper'],MODE_AUDIOLINKS,icon,scrapers.urltools.DictToUrl(line))

                

#------------------------------------------------------------------------------------------------
def VIDEOLINKS(channel):
        params=scrapers.urltools.GetParams(channel)
        name = urllib.unquote_plus(params['name'])

        if name.lower()=='system update':
                UpdateScraperFile()
                dialog = xbmcgui.Dialog()
                dialog.ok("System Update", " System Update was a success ")
                return

        pDialog = xbmcgui.DialogProgress()
        name = scrapers.urltools.RemoveUnicodeCodes(name)
        ret = pDialog.create(name, 'Opening Video Stream...')

        scraper = urllib.unquote_plus(params['scraper'])
        url = urllib.unquote_plus(params['url'])
        scraperobj = scrapers.GetScraperObj(scraper)
        scraperobj.PlayVideo(channel)

#------------------------------------------------------------------------------------------------
def AUDIOLINKS(channel):

        params=scrapers.urltools.GetParams(channel)
        name = urllib.unquote_plus(params['name'])

        pDialog = xbmcgui.DialogProgress()
        ret = pDialog.create(name, 'Opening Audio Stream...')

        scraper = urllib.unquote_plus(params['scraper'])
        url = urllib.unquote_plus(params['url'])
        scraperobj = scrapers.GetScraperObj(scraper)
        scraperobj.PlayAudio(channel)

#------------------------------------------------------------------------------------------------
def get_params():
#['plugin://plugin.video.tugatvdev/|scraper=tugascraper|mode=1|name=SIC|channel=%7Curl%3Dhttp%3A%2F%2Ftugatesting.googlecode.com%2Fsvn%2Ftrunk%2Fchannels%2Fsic.txt%7Ctype%3Ddir%7Cname%3DSIC%7Cscraper%3Dtugascraper?url=http%3A%2F%2Ftugatesting.googlecode.com%2Fsvn%2Ftrunk%2Fchannels%2Fsicpage.txt|scraper=tugascraper|mode=1|name=SIC+Informa%E7%E3o|channel=%7Curl%3Dhttp%3A%2F%2Ftugatesting.googlecode.com%2Fsvn%2Ftrunk%2Fchannels%2Fsicpage.txt%7Ctype%3Ddir%7Cname%3DSIC+Informa%E7%E3o%7Cscraper%3Dtugascraper', '0', '']
        param=[]
        paramstring=sys.argv[0]
        if len(paramstring)>=2:
                params=sys.argv[0]
                cleanedparams=params.replace('?','')
                if (params[len(params)-1]=='/'):
                        params=params[0:len(params)-2]
                print 'cleanedparams: '+cleanedparams
                pairsofparams=cleanedparams.split('|')
                param={}
                for i in range(len(pairsofparams)):
                        splitparams={}
                        splitparams=pairsofparams[i].split('=')
                        if (len(splitparams))==2:
                                param[splitparams[0]]=splitparams[1]
                                
        return param

#------------------------------------------------------------------------------------------------
def addDownLinkVideo(name,url,scraper,mode,iconimage,channel):

        name = name.replace('&quot;','"')
        name = name.replace('&amp;','&')
        name = scrapers.urltools.RemoveUnicodeCodes(name)
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"|scraper="+urllib.quote_plus(scraper)+"|mode="+str(mode)+"|name="+urllib.quote_plus(str(name))+"|channel="+urllib.quote_plus(str(channel))
        ok=True
        localicon=os.path.join( os.getcwd(), "icons", iconimage )
        if scrapers.FileExists(localicon):
            thumbnail=localicon
        else:
            thumbnail=iconimage
        thumbnail = thumbnail.strip()
        print 'thumbnail: '+thumbnail
        liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=thumbnail)
        liz.setInfo( type="Video", infoLabels={ "Title": name } )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
        return ok

#------------------------------------------------------------------------------------------------
def addDownLinkAudio(name,url,scraper,mode,iconimage,channel):

        name = name.replace('&quot;','"')
        name = name.replace('&amp;','&')
        name = scrapers.urltools.RemoveUnicodeCodes(name)
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"|scraper="+urllib.quote_plus(scraper)+"|mode="+str(mode)+"|name="+urllib.quote_plus(str(name))+"|channel="+urllib.quote_plus(str(channel))
        ok=True
        localicon=os.path.join( os.getcwd(), "icons", iconimage )
        if scrapers.FileExists(localicon):
            thumbnail=localicon
        else:
            thumbnail=iconimage
        thumbnail = thumbnail.strip()
        print 'thumbnail: '+thumbnail
        liz=xbmcgui.ListItem(name, iconImage="DefaultAudio.png", thumbnailImage=thumbnail)
        liz.setInfo( type="Audio", infoLabels={ "Title": name } )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
        return ok

#------------------------------------------------------------------------------------------------
def addDir(name,url,scraper,mode,iconimage,channel):

        name = name.replace('&quot;','"')
        name = name.replace('&amp;','&')
        name = scrapers.urltools.RemoveUnicodeCodes(name)
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"|scraper="+urllib.quote_plus(scraper)+"|mode="+str(mode)+"|name="+urllib.quote_plus(name)+"|channel="+urllib.quote_plus(str(channel))
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels={ "Title": name } )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
        return ok
        
#------------------------------------------------------------------------------------------------
params=get_params()
url=None
channel=None
name=None
mode=None
pageurl=None
scraper=None
type=None

pDialog = xbmcgui.DialogProgress()
ret = pDialog.create('Tuga Media Center', 'Please Wait...')

try:
        mode=int(params["mode"])
except:
        mode=MODE_INDEX
try:
        url=urllib.unquote_plus(params["url"])
except:
        url=RootUrl
try:
        channel=urllib.unquote_plus(params["channel"])
except:
        channel='|name=Tuga Media Center|scraper=tugascraper|url='+url


print "_MAIN_"
print "url: "+str(url)
print "name: "+str(name)
print "params: "+str(params)

if mode==MODE_INDEX:
        print "MODE_INDEX: "+channel
        INDEX(channel)
elif mode==MODE_VIDEOLINKS:
        print "MODE_VIDEOLINKS: "
        VIDEOLINKS(channel)
elif mode==MODE_AUDIOLINKS:
        print "MODE_AUDIOLINKS: "
        AUDIOLINKS(channel)

xbmcplugin.endOfDirectory(int(sys.argv[1]))

#------------------------------------------------------------------------------------------------
